package com.quarantine.service;

import java.util.Date;
import java.util.Set;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.GrantedAuthorityImpl;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.transaction.annotation.Transactional;

import com.google.common.collect.Sets;
import com.quarantine.model.administrator;
import com.quarantine.util.OperatorDetails;

/**
 * 实现SpringSecurity的UserDetailsService接口,实现获取用户Detail信息的回调函数.
 * 
 * 演示扩展SpringSecurity的User类加入loginTime信息.
 * 
 * @author calvin
 */
@SuppressWarnings("deprecation")
@Transactional(readOnly = true)
public class AdminDetailsServiceImpl implements UserDetailsService {

	private AdministratorManager administratorManager;

	/**
	 * 获取用户Detail信息的回调函数.
	 */
	public UserDetails loadUserByUsername(String username)
			throws UsernameNotFoundException, DataAccessException {

		administrator user = administratorManager.findByLoginName(username);
		if (user == null) {
			throw new UsernameNotFoundException("用户" + username + " 不存在");
		}

		Set<GrantedAuthority> grantedAuths = obtainGrantedAuthorities(user);

		boolean employeeNonExpired = true;
		boolean credentialsNonExpired = true;
		boolean employeeNonLocked = true;

		OperatorDetails userDetails = new OperatorDetails(user.getLoginName(),
				user.getPassword(), true, employeeNonExpired,
				credentialsNonExpired, employeeNonLocked, grantedAuths);
		// 加入登录时间信息和用户角色
		//userDetails.setEmployee(user);
		userDetails.setLoginTime(new Date());
		//userDetails.setRoleList(user.getRoles());

		return userDetails;
	}

	/**
	 * 获得用户所有角色的权限.
	 */
	private Set<GrantedAuthority> obtainGrantedAuthorities(administrator user) {
		Set<GrantedAuthority> authSet = Sets.newHashSet();
		/*
		 * for (Role role : user.getRoles()) { for (Authority authority :
		 * role.getAuthorities()) authSet.add(new GrantedAuthorityImpl(authority
		 * .getPrefixedName())); }
		 */
		authSet.add(new GrantedAuthorityImpl("back"));
		return authSet;
	}

	@Autowired
	public void setAdministratorManager(
			AdministratorManager administratorManager) {
		this.administratorManager = administratorManager;
	}

}
